package com.vision.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.vision.mapper.VideoHistoryMapper;
import com.vision.pojo.entity.VideoHistory;
import com.vision.pojo.vo.PageVO;
import com.vision.pojo.vo.VideoHistoryVO;
import com.vision.service.VideoHistoryService;
import com.vision.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @projectName: vision
 * @package: com.vision.service.impl
 * @className: VideoHistoryServiceImpl
 * @author: escapeicon@gmail.com
 * @description: 视频历史记录服务实现
 * @date: 2024/1/28 14:02
 * @version: 1.0
 */
@Service
public class VideoHistoryServiceImpl implements VideoHistoryService {
    @Autowired
    private VideoHistoryMapper videoHistoryMapper;

    /**
     * 添加视频历史记录
     * @param videoId 视频ID
     */
    @Override
    public void addVideoHistory(Integer videoId) {
        // 1. 获取当前登录用户 ID
        Map<String, Integer> claims = ThreadLocalUtil.get();
        Integer userId = claims.get("id");
        // 2. 查询是否已存在历史记录
        VideoHistory videoHistory = videoHistoryMapper.selectByUserIdAndVideoId(userId, videoId);
        // 3. 如果存在历史记录则更新时间
        if (videoHistory != null) {
            // 3.1 更新时间
            videoHistoryMapper.updateTime(userId,videoId);
        } else {
            // 3.2 添加历史记录
            videoHistoryMapper.insert(videoId,userId);
        }

    }

    /**
     * 获取视频历史记录
     * @param pageNum 页码
     * @param pageSize 页数
     * @return PageVO<VideoHistoryVO>
     */
    @Override
    public PageVO<VideoHistoryVO> getVideoHistoryForPage(Integer pageNum, Integer pageSize) {
        // 1. 获取当前用户 ID
        Map<String, Integer> claims = ThreadLocalUtil.get();
        Integer userId = claims.get("id");
        // 2. 创建 pageVO 对象
        PageVO<VideoHistoryVO> pageVO = new PageVO<>();
        // 3. 开启分页
        PageHelper.startPage(pageNum,pageSize);
        // 4. 查询数据
        List<VideoHistoryVO> list = videoHistoryMapper.selectByUserId(userId);
        // 5. 向下转型
        Page<VideoHistoryVO> videoHistoryList = (Page<VideoHistoryVO>) list;
        // 6. 设置数据
        pageVO.setItems(videoHistoryList.getResult());
        pageVO.setTotal(videoHistoryList.getTotal());
        pageVO.setPageNum(pageNum);
        pageVO.setPageSize(pageSize);
        // 7. 返回数据
        return pageVO;
    }
}
